package pers.zc.activiti.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @description zookeeper 使用
 * @Author Lin FuYuan
 * @date 2020/4/14
 */
public class HelloZookeeper implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //zookeeper配置数据存放路径
        String path = "/username";
        //连接zookeeper并且注册一个默认的监听器
        zk = new ZooKeeper("172.24.103.135:2181", 5000, new HelloZookeeper());
        //等待zk连接成功的通知
        connectedSemaphore.await();
        //获取path目录节点的配置数据，并注册默认的监听器
        System.out.println(new String(zk.getData(path, true, stat)));
//        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        //zk连接成功通知事件
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            System.out.println(watchedEvent.getType() );
            if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) {
                connectedSemaphore.countDown();
                System.out.println("当前计数"+connectedSemaphore.getCount());
                //zk目录节点数据变化通知事件
            } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
                try {
                    System.out.println("配置已修改，新值为：" + new String(zk.getData(watchedEvent.getPath(), true, stat)));
                } catch (Exception e) {
                }
            }
            else if(watchedEvent.getType() == Event.EventType.NodeDeleted){
                System.out.println("节点已删除");
            }else if(watchedEvent.getType() == Event.EventType.None){
                System.out.println("节点不存在");
            }
        }
    }
}
